//
//  PaperCardView.m
//  ZYOnlineSchool
//
//  Created by 毕武侠 on 2017/2/27.
//  Copyright © 2017年 bwx. All rights reserved.
//

#import "PaperCardView.h"
#import "HeadTopView.h"
#import "PaperCardCollectionView.h"
#import "PaperModuleModel.h"
#import "NSString+Additions.h"

@interface PaperCardView () <didSelectCollectionDelegate>

@property (strong, nonatomic) HeadTopView *headView;
@property (strong, nonatomic) UILabel *titleLab;
@property (strong, nonatomic) UIView  *lineView;

@property (strong, nonatomic) UIButton *sendBtn;

@property (strong, nonatomic) RACSubject *subject;

/** 答题花费的时间数值 */
@property (nonatomic, strong, readwrite) UILabel  *timerLabel;      // 时间
@property (nonatomic, strong) NSTimer  *timer;           // 答题计时器
/** 用户答题花费的时间数值 */
@property (nonatomic, assign) NSInteger duration;

//@property (nonatomic, strong, readwrite) RACSubject *submitSubject_;
@property (nonatomic, strong) UIAlertView *alertView;



@end

@implementation PaperCardView

- (instancetype)init {
    self = [super init];
    if (self) {
        [self initConfigureView];
        
        
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self initConfigureView];
    }
    return self;
}

- (void)initConfigureView {
    self.subject = [RACSubject subject];
//    self.submitSubject_ = [RACSubject subject];
    self.backgroundColor = [UIColor colorWithHexString:@"f4f4f4"];

    self.showTimerView = YES;
    self.showTopView = YES;
    self.showTitleView = YES;
    self.showCollectView = YES;
    self.showSendView = YES;
}

- (void)setupConfigure {
    CGFloat top = 0;
    if (self.showTopView == YES) {
        self.headView = [[HeadTopView alloc] initWithFrame:CGRectMake(0, top, SCREEN_WIDTH, kNavigationBarHeight)];
        top = 64;
        self.headView.text = @"答题卡";
        self.headView.showLeft = YES;
        self.headView.leftImageName = @"palette_back";
        @weakify(self)
        [[self.headView getSignalWithDictionary:@{@"action" : @"left"}] subscribeNext:^(id x) {
            @strongify(self)
            [self hiddenWithAnimation:YES];
        }];
        [self addSubview:self.headView];
    }
    
    if (self.showTopView == YES && self.showTimerView == YES) {
        self.timerLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 108, kStatusBarHeight, 94, 44)];
        self.timerLabel.textColor = [UIColor whiteColor];
        self.timerLabel.textAlignment = NSTextAlignmentRight;
        self.timerLabel.text = @"00 : 00";
        [self addSubview:self.timerLabel];
    }
    
    if (self.showTitleView == YES) {
        self.titleLab.frame = CGRectMake(12, top, SCREEN_WIDTH - 24.0, 32);
//        self.titleLab.backgroundColor = [UIColor redColor];
        [self addSubview:self.titleLab];
        
        self.lineView.frame = CGRectMake(0, self.titleLab.bottom - 1, SCREEN_WIDTH, 1);
        [self addSubview:self.lineView];
        
        top = self.lineView.bottom;
    }
    
    if (self.showCollectView == YES) {
        self.collectionView.frame = CGRectMake(0, top, SCREEN_WIDTH, self.height - top-kBottomSafeHeight);
        top = self.collectionView.bottom;
        [self addSubview:self.collectionView];
    }
    
    if (self.showSendView == YES) {
        self.collectionView.height = self.collectionView.height - 42.0f;
        self.sendBtn.frame = CGRectMake(0, self.height - 42 - kBottomSafeHeight, SCREEN_WIDTH, 42+kBottomSafeHeight);
        [self addSubview:self.sendBtn];
    }
}

#pragma mark time action
/** 开始计时⌛️ */
- (void)startTimer {
    if (self.timer == nil) {
        self.timerLabel.text = [NSString TimeformatFromSeconds:self.duration];
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(clockingAsc) userInfo:nil repeats:YES];
    } else {
        [self.timer setFireDate:[NSDate distantPast]];
    }
}

/** 结束计时⌛️ */
- (void)endTimer {
    if ([self.timer isValid]) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

/** 暂停计时⌛️*/
- (void)pauseTimer {
    [self.timer setFireDate:[NSDate distantFuture]];
}

// 正计时⌛️
- (void)clockingAsc {
    self.duration++;
    if (self.surplus != 0 && self.duration >= self.surplus) {       // 到达最大时间
        [self pauseTimer];
    }
    self.timerLabel.text = [NSString TimeformatFromSeconds:self.duration];
}

- (void)setSourceDatas:(NSMutableArray *)sourceData {
    if (self.isInit == NO) {
        self.isInit = YES;
        [self setupConfigure];
    }
    self.collectionView.sourceData = sourceData;
}

- (void)updateView {
    if (self.showCollectView == YES) {
        [self.collectionView reloadData];
    }
}

- (void)showWithAnimation:(BOOL)animation withTime:(NSUInteger)time {
    self.duration = time;
    if (self.showTimerView == YES) {
        [self startTimer];
    }
    
    [self.collectionView reloadData];
    [self showWithAnimation:animation];
}

- (void)showWithAnimation:(BOOL)animation {
    if (self.alpha == 1.0) return;
    
    if (animation == NO) {
        self.alpha = 1.0;
    } else {
        [UIView animateWithDuration:0.35 animations:^{
            self.alpha = 1.0;
        }];
    }
}

- (void)hiddenWithAnimation:(BOOL)animation {
    if (self.alpha == 0.0) return;
    
    if (animation == NO) {
        self.alpha = 0.0;
    } else {
        [UIView animateWithDuration:0.35 animations:^{
            self.alpha = 0.0;
        }];
    }
    [self pauseTimer];
}


#pragma mark - didSelectCollectionDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectIndexPath:(NSIndexPath *)indexPath {
    [self.subject sendNext:indexPath];
    if (self.didHidden == YES) {
        [self hiddenWithAnimation:YES];
    }
}

#pragma mark - ViewSignalProtocol

- (RACSignal *)getSignalWithDictionary:(NSDictionary *)dict {
    NSString *str = dict[@"action"];
    if (!str)   return [RACSignal empty];
    
    if ([str isEqualToString:@"select"]) {           // 跳转index
        return self.subject;
//    }  else if ([str isEqualToString:@"send"]) {     // 发送
//        return [[self.sendBtn rac_signalForControlEvents:UIControlEventTouchUpInside] map:^id(id value) {
//            NSMutableArray *answer_data = [NSMutableArray array];
//            __block NSString *report_id = nil;
//            __block NSString *paper_id = nil;
//            
//            [self.collectionView.sourceData enumerateObjectsUsingBlock:^(PaperModuleModel *moduleModel, NSUInteger idx, BOOL * _Nonnull stop) {
//                if (paper_id == nil && moduleModel.paper_id) {
//                    paper_id = moduleModel.paper_id;
//                }
//                [moduleModel.module_question enumerateObjectsUsingBlock:^(PaperAnswerModel * _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
//                    [answer_data addObject:@{@"ques_id" : model.ques_id ? : @"", @"user_answer" : model.answer ? : @""}];
//                    if (report_id == nil && model.report_id) {
//                        report_id = model.report_id;
//                    }
//                    
//                }];
//            }];
//                                           
//            NSMutableDictionary *dic = @{@"answer_data" : answer_data,
//                                         @"report_id"   : report_id ? : @"",
//                                         @"paper_id"    : paper_id ? : @""}.mutableCopy;
//
//            
//            return dic;
//        }];
    } else {
        return [RACSignal empty];
    }
}
- (void)submitBtnClick:(UIButton *)btn{
    [self showalert];
}

- (void)showalert{
    if (self.collectionView.sourceData == 0) {                // 没有数据，直接退出
        //        [self.exitSignal sendNext:nil];
    } else {
        __block NSUInteger selectIndex = 0;
        __block NSUInteger allIndex = 0;
        
        [self.collectionView.sourceData enumerateObjectsUsingBlock:^(PaperModuleModel *moduleModel, NSUInteger idx, BOOL * _Nonnull stop) {
            allIndex += moduleModel.module_question.count;
            
            [moduleModel.module_question enumerateObjectsUsingBlock:^(PaperBaseModel * model, NSUInteger idx, BOOL * _Nonnull stop) {
                if ((model.ques_model == 0 || model.ques_model == 1) && model.index != NSNotFound) {
                    selectIndex++;
                } else if ((model.ques_model == 2 || model.ques_model == 3) && model.user_content.length > 0) {
                    selectIndex++;
                }
            }];
        }];
        
        if (selectIndex == 0) {
            //[self.exitSignal sendNext:nil];    // 有数据，但未作答，直接退出
            self.alertView.message = [NSString stringWithFormat:@"您尚有%ld题未答，确定交卷吗？", allIndex - selectIndex];
            [self.alertView show];
            return;
            
        } else {
            if (selectIndex == allIndex) {
                //                self.alertView.message = @"您已全部作答完成，确定要退出本次答题？";
                [self sendData];
                return;
            } else {
                self.alertView.message = [NSString stringWithFormat:@"您尚有%ld题未答，确定交卷吗？", allIndex - selectIndex];
                [self.alertView show];
                return;
            }
            
        }
    }
    
}
- (void)sendData{
//    NSMutableArray *answer_data = [NSMutableArray array];
//    __block NSString *report_id = nil;
//    __block NSString *paper_id = nil;
//
//    [self.collectionView.sourceData enumerateObjectsUsingBlock:^(PaperModuleModel *moduleModel, NSUInteger idx, BOOL * _Nonnull stop) {
//        if (paper_id == nil && moduleModel.paper_id) {
//            paper_id = moduleModel.paper_id;
//        }
//        [moduleModel.module_question enumerateObjectsUsingBlock:^(PaperAnswerModel * _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
//            [answer_data addObject:@{@"ques_id" : model.ques_id ? : @"", @"user_answer" : model.answer ? : @""}];
//            if (report_id == nil && model.report_id) {
//                report_id = model.report_id;
//            }
//
//        }];
//    }];
//
//    NSMutableDictionary *dic = @{@"answer_data" : answer_data,
//                                 @"report_id"   : report_id ? : @"",
//                                 @"paper_id"    : paper_id ? : @""}.mutableCopy;

    //[self.submitSubject_ sendNext:dic];
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_SENDPAPER object:nil];

//    return dic;

}

- (UIAlertView *)alertView {
    if (_alertView == nil) {
        _alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    }
    return _alertView;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex) {
        //[self.exitSignal sendNext:nil];         // 有数据，作答了几道题，但仍然退出
        [self sendData];
    }
}
#pragma mark - setter 

- (void)setShowTimerView:(BOOL)showTimerView {
    _showTimerView = showTimerView;
    self.timerLabel.hidden = !showTimerView;
}

- (void)setShowSendView:(BOOL)showSendView {
    
    self.sendBtn.hidden = !showSendView;
    if (showSendView == NO) {
        if (_showSendView == YES) {
            self.collectionView.height = self.collectionView.height + 42.0f;
            self.sendBtn.frame = CGRectMake(0, self.height, SCREEN_WIDTH, 0);
        }
    } else {
        if (_showSendView == NO) {
            self.collectionView.height = self.collectionView.height - 42.0f;
            self.sendBtn.frame = CGRectMake(0, self.height - 42, SCREEN_WIDTH, 42);
        }
    }
    
    _showSendView = showSendView;
}

- (void)setShowTitleView:(BOOL)showTitleView {
    _showTitleView = showTitleView;
    self.titleLab.hidden = !showTitleView;
    self.lineView.hidden = !showTitleView;
}

#pragma mark - getter

- (UILabel *)titleLab {
    if (_titleLab == nil) {
        _titleLab = [[UILabel alloc] init];
        _titleLab.textColor = [UIColor darkGrayColor];
        _titleLab.text = @"";
    }
    return _titleLab;
}

- (UIView *)lineView {
    if (_lineView == nil) {
        _lineView = [[UIView alloc] init];
        _lineView.backgroundColor = RGB(234, 234, 234);
    }
    return _lineView;
}

- (PaperCardCollectionView *)collectionView {
    if (_collectionView == nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        _collectionView = [[PaperCardCollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.height) collectionViewLayout:layout];
        _collectionView.minInteritemSpace = 32.0f;
        _collectionView.minLineSpace = 24.0f;
        _collectionView.didDatagate = self;
        _collectionView.edgeInsets = UIEdgeInsetsMake(4, 16.0f, 16.0f, 16.0f);
    }
    return _collectionView;
}

- (UIButton *)sendBtn {
    if (_sendBtn == nil) {
        _sendBtn = [[UIButton alloc] init];
        _sendBtn.backgroundColor = MainThemeColor;
        [_sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_sendBtn setTitle:@"提交" forState:UIControlStateNormal];
        [_sendBtn addTarget:self action:@selector(submitBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendBtn;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
